<script setup lang="ts">
import { request } from '@/api'
import {
  closeToast,
  showLoadingToast,
  showSuccessToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import b64toBlob from 'b64-to-blob'

// 相册上传
const showAvatarSheet = ref(false)
const showAvatarActions = [{ name: '拍照上传' }, { name: '相册上传' }]
const onSelectAvatar = async (action: ActionSheetAction, index: number) => {
  if (index == 0) {
    const res = await mk.pickerCamera()
    await onUpdateAvatar(res)
  } else {
    // console.log('相册上传')
    const res = await mk.pickerPhoto()
    await onUpdateAvatar(res) 
  }
}

// 更新头像
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({
      message: '正在上传中...',
      forbidClick: true,
      duration: 0,
    })
    // base64字符串转二进制
    const img = b64toBlob(data, 'image/jpeg')
    // 创建上传服务器对象
    const fd = new FormData()
    fd.append('file', img, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    closeToast()
    // 更新本地用户信息
    profile.value.avatar = res.data.result.avatar
    const user = mk.queryUser()
    // 重新存储到用户
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast('上传成功')
  } catch (e) {
    console.log(e)
    showToast('上传失败')
  }
}

// 选择生日
const showBirthdayPopup = ref(false)
const birthday = ref(['2000', '1', '1'])
const onConfirm = () => {
  // console.log(data)
  // 通过 - 进行拼接
  profile.value.birthday = birthday.value.join('-')
  showBirthdayPopup.value = false
}

// 展示所在地
const showLocationPopup = ref(false)
const areaList = ref<AreaColumns>()
onMounted(async () => {
  const data = await mk.getAreaColumns()
  // console.log(data)
  areaList.value = data
})

// 选择所在地
const onSelectedLocation = (data: { selectedValues: number[] }) => {
  showLocationPopup.value = false
  // console.log(data)
  const province = areaList.value?.province_list[data.selectedValues[0]]
  const city = areaList.value?.city_list[data.selectedValues[1]]
  const county = areaList.value?.county_list[data.selectedValues[2]]
  // 城市数字码
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  // console.log(province, city, county);
  // 更新本地城市显示
  profile.value.fullLocation = `${province} ${city} ${county}`
  showLocationPopup.value = false
}

// 用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  })
  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  closeToast()
  // 通过 - 进行拆解成数组
  birthday.value = res.data.result.birthday.split('-')
  // 赋值给本地
  profile.value = res.data.result
  // console.log(profile.value)
})

// 选择职位
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  // console.log(data)
  profile.value.profession = data.selectedValues[0]
  showProfessionPopup.value = false
}

// 保存按钮
const loading = ref(false)
const onsubmit = async () => {
  loading.value = true
  // 本地用户数据提交给网络服务器
  const res = await request.put<MkResponse<ProfileInfo>>(
    'member/profile',
    profile.value,
  )
  mk.updateUser(res.data.result)
  loading.value = false
  showSuccessToast('保存成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <van-toast />
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <!-- 底部模态 -->
    <van-action-sheet
      v-model:show="showAvatarSheet"
      style="padding-bottom: 20px"
      :actions="showAvatarActions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelectAvatar"
    />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field
        label="昵称"
        v-model="profile.nickname"
        placeholder="请输入昵称"
      ></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        @click="showBirthdayPopup = true"
        placeholder="请选择日期"
        v-model="profile.birthday"
      ></van-field>
      <van-popup
        v-model:show="showBirthdayPopup"
        style="border-radius: 10px 10px 0px 0px"
        position="bottom"
      >
        <van-date-picker
          v-model="birthday"
          title="选择日期"
          :min-date="new Date(1975, 1, 1)"
          :max-date="new Date()"
          @confirm="onConfirm"
          @cancel="showBirthdayPopup = false"
          style="padding-bottom: 20px"
        />
      </van-popup>

      <van-field
        label="所在地"
        v-model="profile.fullLocation"
        readonly
        @click="showLocationPopup = true"
        placeholder="请选择所在地"
      ></van-field>
      <van-popup v-model:show="showLocationPopup" round position="bottom">
        <!-- 地址选择滚动 -->
        <van-area
          :area-list="areaList"
          @confirm="onSelectedLocation"
        ></van-area>
      </van-popup>

      <van-field
        label="职业"
        v-model="profile.profession"
        readonly
        placeholder="请选择职业"
        @click="showProfessionPopup = true"
      ></van-field>
      <van-popup v-model:show="showProfessionPopup" round position="bottom">
        <van-picker
          :columns="columns"
          @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false"
        />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button
        :loading="loading"
        loading-text="加载中..."
        round
        block
        type="primary"
        @click="onsubmit"
      >
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
